#pragma once
#include "SThread.h"
#include "XAudio2.h"
#include <fstream>
#include "SD2D.h"
#include "Famicom.h" 
class MainWindow;
class FamicomThread :public SThread,public IFcEvent
{
private:
	HANDLE mSyncLock = nullptr;
	BOOL loadrom = false;
	Famicom* famicom = nullptr;
	XAudio2* xa2 = nullptr;
	std::fstream* savefs = nullptr;
	SD2D* d2d = nullptr;
	enum
	{
		EVENT_RELOADROM = 0x1,
		EVENT_SAVE_STATE = 0x2,
		EVENT_RESTORE_STATE = 0x4,
		EVENT_PAUSE = 0x8,
	};
	int EVENT_FLAG = 0;
	MainWindow* nesmain = nullptr;

public:
	WCHAR filename[1024] = {0};
	FamicomThread(MainWindow* nesmain);
	float FPS = 0;

	void WaitSyncLock();
	void ReleaseSyncLock();
	void Play();
	void Pause();
	void Save();
	void Restore();
	void GetFrameBuffer(int32_t* dstbuffer, int size);
	void Input(UINT8 index, UINT8 state);
	~FamicomThread();
	void SyncLoadRom(WCHAR* strFilename);
	virtual int Run();

	//IFcEvent
	virtual bool OnSaveBundleOpen(bool issave)override;
	virtual bool OnSaveBundleClose()override;
	virtual void OnSaveBundleWrite(char* buf, int size)override;
	virtual void OnSaveBundleRead(char* buf, int size)override;
	virtual void OnAudioWrite(short* buf, int size)override;
};

